package cn.xshi.common.threadTool;

import org.springframework.stereotype.Component;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
/**
 * @Desc 任务分解
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
public class ForkJoinUtil {
    private static ForkJoinUtil instance = null;
    private ForkJoinPool forkjoinpool;//线程池
    private int maxPoolSize;//最大线程数
    public int getMaxPoolSize() {
        return maxPoolSize;
    }
    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }
    public ForkJoinUtil(){
        //获取本系统的有效线程数，设置线程池为有效线程的两倍。
        int size = Runtime.getRuntime().availableProcessors();
        maxPoolSize = size*2;
        forkjoinpool = new ForkJoinPool(maxPoolSize);
        instance = this;
    }
    public ForkJoinUtil(int maxPoolSize){
        //获取本系统的有效线程数，设置线程池为有效线程的两倍。
        int size = Runtime.getRuntime().availableProcessors();
        if(maxPoolSize>size){
            maxPoolSize = size;
        }
        maxPoolSize = size*2;
        forkjoinpool = new ForkJoinPool(maxPoolSize);
        instance = this;
    }
    public void stop(){
        if(forkjoinpool != null){
            forkjoinpool.shutdown();
        }
    }
    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task){//将任务提交给线程，去执行。 返回值
        return forkjoinpool.submit(task);
    }

    public <T> T invoke(ForkJoinTask<T> task){ //同步 阻塞
        return forkjoinpool.invoke(task);
    }
}
